package my.webservices;

import java.util.List;

import my.webservices.beans.AddVehicleHistoryRequest;
import my.webservices.beans.AddVehicleHistoryResponse;
import my.webservices.beans.Vehicle;
import my.webservices.beans.VehicleHistorySearchRequest;
import my.webservices.beans.VehicleHistorySearchResponse;
import my.webservices.exception.NoVehHistFound;
import my.webservices.model.VehicleHistoryDataManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * VehicleHistorySearchServiceImpl is an implementation of
 * {@link VehicleHistorySearchService}. This service uses the Domain Service
 * Owner Transaction Design Pattern for transaction management.
 * 
 * @author Nilaksh Bajpai.
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public class VehicleHistoryServiceImpl implements VehicleHistoryService {

	private VehicleHistoryDataManager model;

	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * @see my.webservices.VehicleHistoryService#getVehicleHistory(my.webservices.beans.VehicleHistorySearchRequest)
	 */
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public VehicleHistorySearchResponse getVehicleHistory(
			VehicleHistorySearchRequest input) {
		List<Vehicle> vehicle = null;

		if (input != null) {
			vehicle = model.getVehiclesWithHistory(input.getCriteria());
		}

		if (vehicle == null) {
			throw new NoVehHistFound();
		}
		VehicleHistorySearchResponse response = new VehicleHistorySearchResponse();
		response.setVehicles(vehicle);
		return response;
	}

	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public void setModel(VehicleHistoryDataManager model) {
		this.model = model;
	}

	/**
	 * @see my.webservices.VehicleHistoryService#addVehicleHistory(my.webservices.beans.AddVehicleHistoryRequest)
	 */
	public AddVehicleHistoryResponse addVehicleHistory(
			AddVehicleHistoryRequest input) {
		AddVehicleHistoryResponse response = new AddVehicleHistoryResponse();
		Vehicle vehicle = null;
		if (input != null) {
			vehicle = input.getVehicle();
			model.save(vehicle);
			response.setVehicle(vehicle);
		}
		return response;
	}
}